<template>
  <div class="viewContain">
    <!-- 查询列表数据 ok -->
    <el-form :model="listQuery" size="small" label-width="100px">
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 12 }">
          <el-form-item label="apk类型 :">
            <el-select v-model="listQuery.apkClass" clearable placeholder="请选择:">
              <el-option
                v-for="item in apkTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 12 }">
          <el-form-item label="apk名称 :">
            <el-input
              v-model="listQuery.apkName"
              placeholder="apk名称"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 12 }">
          <el-form-item label="apk版本 :">
            <el-input
              v-model="listQuery.apkVersion"
              placeholder="apk版本"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 12 }">
          <el-form-item>
            <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
            <el-button size="mini" type="primary" plain @click="resetInput">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
          <el-form-item style="float:right;">
            <el-button size="mini" type="primary" @click="handleAdd">上传</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 上传 界面 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="500px"
    >
      <div id="loadingContainer" class="loadingContainer">
        <img src="https://img.lanrentuku.com/img/allimg/1212/5-121204193R5-50.gif" alt="">
      </div>
      <el-form ref="formData" style="padding:0;height:420px;border:none;" :model="formData" size="small" label-width="120px" class="dialogFormHeight" :rules="rules">
        <el-form-item label="版本文件:" prop="file" @input="change()">
          <el-upload action="#" :limit="1" :on-exceed="handleExceed" :before-upload="beforeFileUpload" style="float:left">
            <el-button slot="trigger" size="mini" icon="el-icon-document" type="primary">选择文件</el-button>
            <span style="white-space: nowrap;text-overflow:ellipsis; overflow:hidden;">{{ fileName }}<span /></span></el-upload>
        </el-form-item>
        <el-form-item label="apk版本 :" prop="apkVersion">
          <el-input v-model="formData.apkVersion" placeholder="最多输入20字" clearable style="max-width:300px" @input="change()" />
        </el-form-item>
        <el-form-item label="build版本序号:" prop="build">
          <el-input v-model="formData.build" clearable style="max-width:300px" @input="change()" @blur="checkBuild()" />
        </el-form-item>
        <el-form-item label="升级方式 :" prop="type">
          <el-select v-model="formData.type" style="width:300px" clearable placeholder="请选择:">
            <el-option
              v-for="item in updateTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="apk类型 :" prop="apkClass">
          <el-select v-model="formData.apkClass" style="width:300px;" placeholder="请选择" clearable @input="change()" @change="checkBuild()">
            <el-option
              v-for="item in apkTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="版本说明:" prop="explanation">
          <el-input v-model="formData.explanation" type="textarea" placeholder="最多可以输入100字" style="max-width:300px;" />
        </el-form-item>
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <div style="text-align:right;margin:0 auto;width:130px;">
              <el-button size="mini" type="primary" @click="handleSave">提交</el-button>
              <el-button size="mini" type="primary" @click="handleClose">关闭</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 列表数据ok -->
    <el-table
      ref="table"
      v-loading="loading"
      fit
      stripe
      :data="tableData"
      border
      size="mini"
    >
      <el-table-column align="center" label="序号" type="index">
        <template slot-scope="scope">
          <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="apkClass" align="center" label="apk类型" width="110" />
      <el-table-column prop="apkName" align="center" label="apk名称" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="apkVersion" align="center" label="apk版本" width="80" :show-overflow-tooltip="true" />
      <el-table-column prop="build" align="center" label="build版本" width="80" />
      <el-table-column prop="type" align="center" label="升级方式" width="90" />
      <el-table-column prop="apkSize" align="center" label="apk大小(kb)" width="100" />
      <el-table-column prop="explanation" align="center" label="版本说明" :show-overflow-tooltip="true" />
      <el-table-column prop="createTime" align="center" label="上传时间" width="150" />
      <el-table-column align="center" label="操作" width="240" fixed="right">
        <template slot-scope="scope">
          <el-button class="text-button" size="mini" @click="handleBinding(0, scope.row)">设备绑定</el-button>
          <el-button class="text-button" size="mini" @click="handleBinding(1, scope.row)">设备解绑</el-button>
          <el-button class="text-button" size="mini"><a :href="'http://lians.yun.e-tecsun.com'+scope.row.url">下载</a></el-button>
          <el-button class="text-button el-button--danger" size="mini" @click="handleDeleteSoftware(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total-count="totalCount"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script>
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
import pagination from '@/components/pagination/index.vue'
// eslint-disable-next-line no-unused-vars
import { bulidCheck, gainUpdateType, gainSoftwareType, uploadApkVersionFile, getSoftwareInfo, delSoftWareByParams, getAppInfo, getDeviceInfo, getAreaInfo, handleCreateSoftwareVersion, uploadVersionFile, handleVersionLogs, handleUpdateVersionInfo, checkUpDateStatus } from '@a/software/software.js'
export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { pagination },
  mixins: [commonMixin],
  data() {
    return {
      // 查询列表信息接口ok
      comApiUrlList: new ComApiUrl('/autoUpdate/api/autoUpdateInfo/getAutoUpdateList'),
      comApiUrl: new ComApiUrl('/core/api/user/', 'getPageUserList'),
      loading: false,
      dialogFormVisible_detail: false,
      dialogTitle_detail: '',
      buildFlag: true,
      uploadFile: null,
      fileName: '',
      apkTypeList: [{ label: '', value: '' }],
      updateTypeList: [],
      // ok listquery
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        apkClass: '',
        apkName: '',
        apkVersion: ''
      },
      dialogTitle: '新增软件版本',
      dialogFormVisible: false,
      formData: {
        apkVersion: '',
        build: 1,
        type: '',
        apkClass: '',
        explanation: ''
      },
      areaIds: '',
      tableData: [
        {
          apkClass: '',
          apkName: '',
          apkSize: '',
          apkVersion: '',
          build: 0,
          createTime: '',
          explanation: '',
          type: '',
          url: ''
        }
      ],
      rules: {
        apkVersion: [
          {
            required: true, message: 'apk版本不能为空', trigger: 'blur'
          }],
        build: [
          { required: true, message: 'build版本序号不能为空!', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '升级方式不能为空!', trigger: 'blur' }
        ],
        apkClass: [
          { required: true, message: 'apk类型不能为空!', trigger: 'blur' }
        ],
        explanation: [{
          required: true, message: 'apk版本说明不能为空', trigger: 'blur'
        }]
      }
    }
  },
  mounted() {
    this.getList()
    this.getUpdateType()
    this.getApkType()
  },
  methods: {
    getList() {
      this.getInfo()
    },

    change() {
      this.$forceUpdate()
    },
    resetInput() {
      this.listQuery.apkClass = ''
      this.listQuery.apkName = ''
      this.listQuery.apkVersion = ''
      this.getList()
    },

    // 查询 ok
    handleSearch() {
      this.getList()
    },

    // 删除版本信息 ok
    handleDeleteSoftware(data) {
      var msg = '您真的确定要删除吗？\n\n请确认！'
      if (confirm(msg) === true) {
        var apkclass = '不存在apk类型';
        for (var i = 0; i < this.apkTypeList.length; i++) {
          if (data.apkClass === this.apkTypeList[i].label) {
            apkclass = Number(this.apkTypeList[i].value)
            break
          }
        }
        console.log('apkclass: ' + apkclass + 'build:' + Number(data.build))
        if (apkclass === '不存在apk类型') {
          this.$message({
            type: 'error',
            message: 'apk类型不存在'
          })
          return
        }
        // 发送删除请求
        delSoftWareByParams(apkclass, Number(data.build)).then(res => {
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })
      } else {
        console.log('取消')
      }
    },

    // 设备绑定
    handleBinding(type, row) {
      const name = type === 0 ? 'softwareBind' : 'softwareUnbind'
      this.$router.push({
        name,
        query: { id: row.id }
      })
    },

    parseTreeJson(array, arr) {
      for (let index = 0; index < array.length; index++) {
        const element = array[index]
        // 1.判断element.children是对象
        if (element.children) {
          arr.push({ distinctId: element.distinctId, name: element.name })
          this.parseTreeJson(element.children, arr)
        } else {
          arr.push({ distinctId: element.distinctId, name: element.name })
        }
      }
    },

    // 打开上传页面 ok
    handleAdd() {
      this.dialogFormVisible = true
      this.dialogTitle = '上传文件'
      this.formData.type = this.updateTypeList[0].value
      this.formData.apkClass = this.apkTypeList[0].value
    },
    // 获取更新类型数据 ok
    getUpdateType() {
      gainUpdateType().then(res => {
        if (res.code === 0) {
          this.updateTypeList = res.data['AUTO_UPDATE_TYPE']
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 获取apk类型 ok
    getApkType() {
      gainSoftwareType().then(res => {
        if (res.code === 0) {
          this.apkTypeList = res.data['AUTO_UPDATE_APK_TYPE']
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 检测apk类型bulid合法性 bulid失焦，apkclass变化触发此函数，获取两者值校验对应类型的build值是否合法 ok
    checkBuild() {
      const apkclass = this.formData.apkClass
      const bulid = this.formData.build
      bulidCheck(Number(apkclass), bulid).then(res => {
        if (res.code === 0) { console.log('build合法') } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          this.formData.build = 1
          console.log('checkout : false')
        }
      })
    },

    getNowFormatDate() {
      var date = new Date() // datetime时间戳为13位毫秒级别,如为10位需乘1000
      var month = ('0' + (date.getMonth() + 1)).slice(-2)	// getMonth是从1-11,所以需要加1
      var sdate = ('0' + date.getDate()).slice(-2)	// -2表示从倒数第二个元素开始截取
      var hour = ('0' + date.getHours()).slice(-2)
      var minute = ('0' + date.getMinutes()).slice(-2)
      var second = ('0' + date.getSeconds()).slice(-2)
      var thatDate = date.getFullYear() + '-' + month + '-' + sdate + ' ' + hour + ':' + minute + ':' + second
      return thatDate
    },
    // 版本文件上传 ok
    handleSave() {
      const apkclass = this.formData.apkClass
      const bulid = this.formData.build
      // 校验build合法
      bulidCheck(Number(apkclass), bulid).then(res => {
        if (res.code === 0) {
          // 校验上传文件值是否为空
          if (this.uploadFile === null) {
            this.$message({
              type: 'warning',
              message: '上传文件不能为空'
            })
          } else {
            // 所有数据合法 进行表单校验
            this.$refs.formData.validate(valide => {
              if (valide) {
                const newFormData = new FormData()
                newFormData.append('file', this.uploadFile)
                newFormData.append('apkVersion', this.formData.apkVersion)
                newFormData.append('build', this.formData.build)
                newFormData.append('type', this.formData.type)
                newFormData.append('apkClass', this.formData.apkClass)
                newFormData.append('explanation', this.formData.explanation)
                const loadingContainer = document.getElementById('loadingContainer')
                loadingContainer.style.display = 'block'
                uploadApkVersionFile(newFormData).then(res => {
                  if (res.code === 0) {
                    loadingContainer.style.display = 'none'
                    this.$message({
                      type: 'success',
                      message: res.msg
                    })
                    this.$refs.formData.resetFields()
                    this.fileName = ''
                    this.dialogFormVisible = false
                    this.getList()
                  } else {
                    loadingContainer.style.display = 'none'
                    this.$message({
                      type: 'error',
                      message: res.msg
                    })
                  }
                })
              }
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          this.formData.build = 1
        }
      })
    },

    // 关闭修改或新增弹窗
    handleClose() {
      this.$refs.formData.resetFields()
      this.fileName = ''
      this.$forceUpdate()
      this.dialogFormVisible = false
    },

    // 上传之前要干的事情 限制文件大小与类型
    beforeFileUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      const temp = file.name.split('.')
      const fileType = temp[temp.length - 1]
      if (fileType === 'apk') {
        if (isLt100M) {
          this.fileName = file.name
          this.uploadFile = file
          console.log('uploadFile' + this.uploadFile)
          return true
        } else {
          this.$message({
            type: 'warning',
            message: '上传文件大小超出100MB!'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '上传文件必须是apk文件!'
        })
      }
      return false
    },
    // 上传多个文件时进行处理
    handleExceed(files, fileList) {
      this.$message.warning(`限制只能上传1个文件`)
    }
  }
}
</script>

<style lang="scss" scoped>
.loadingContainer{
 position: absolute;
 left: 50%;
 top:50%;
 display: none;
 margin-left: -40px;
 margin-top:-50px;
 z-index: 999;
}
</style>
